package com.livideo.baseutilslibrary.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Random;

public class PhotoUtils {
    /**
     * com.mobile.videonews.li.sciencevideo.fileprovider
     */
    public static final String authorities = "";

    public static Crop crop(FragmentManager manager) {
        return new Crop(manager);
    }

    public static Crop crop(FragmentActivity activity) {
        return new Crop(activity.getSupportFragmentManager());
    }

    public static Crop crop(Fragment fragment) {
        return new Crop(fragment.getChildFragmentManager());
    }

    public static class Crop {
        private FragmentManager manager;
        private int aspectX = 0;
        private int aspectY = 0;
        private int outputX = 0;
        private int outputY = 0;

        public Crop(FragmentManager manager) {
            this.manager = manager;
        }

        public Crop setAspect(int aspectX, int aspectY) {
            if(aspectX < 0){
                aspectX = 0;
            }
            if(aspectY < 0){
                aspectY = 0;
            }
            this.aspectX = aspectX;
            this.aspectY = aspectY;
            return this;
        }

        /**
         * 设置输出图片的宽高
         */
        public Crop setOutput(int width, int height) {
            if(width < 0){
                width = 0;
            }
            if(height < 0){
                height = 0;
            }
            this.outputX = width;
            this.outputY = height;
            return this;
        }

        public void build(Uri uri, PhotoCallback callback){
            crop(manager, uri, aspectX, aspectY, outputX, outputY, callback);
        }
    }

    public static void select(FragmentActivity activity, PhotoCallback callback){
        getPhotoFragment(activity.getSupportFragmentManager()).select(callback);
    }

    public static void camera(FragmentActivity activity, PhotoCallback callback){
        getPhotoFragment(activity.getSupportFragmentManager()).camera(callback);
    }

    private static void crop(FragmentManager manager, Uri uri, int aspectX, int aspectY, int outputX, int outputY, PhotoCallback callback){
        getPhotoFragment(manager).crop(uri, aspectX, aspectY, outputX, outputY, callback);
    }

    public static class PhotoFragment extends Fragment {
        private final int REQUEST_CODE_CROP = 601;
        private final int REQUEST_CODE_CAMERA = 602;
        private final int REQUEST_CODE_SELECT = 603;
        private PhotoCallback cropCallback = null;
        private PhotoCallback selectCallback = null;
        private PhotoCallback cameraCallback = null;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRetainInstance(true);
        }

        String cameraPath;
        //调用相机
        private void camera(PhotoCallback callback) {
            if(TextUtils.isEmpty(authorities)){
                throw new RuntimeException("请填写正确的authority");
            }

            this.cameraCallback = callback;
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            File file = new File(requireContext().getExternalCacheDir().getAbsolutePath(),
                    System.currentTimeMillis()+new Random().nextInt(9999)+".jpg");
            cameraPath = file.getAbsolutePath();
            Uri uri;
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                uri = FileProvider.getUriForFile(requireContext(),authorities,file);
            }else{
                uri = Uri.fromFile(file);
            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, REQUEST_CODE_CAMERA);
        }

        //选择图片
        private void select(PhotoCallback callback) {
            this.selectCallback = callback;
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(
                    intent, REQUEST_CODE_SELECT);
        }

        Uri outUri = null;
        private void crop(Uri uri, int aspectX, int aspectY, int outputX, int outputY, PhotoCallback callback){
            if(TextUtils.isEmpty(authorities)){
                throw new RuntimeException("请填写正确的authority");
            }
            Uri uri1;
            if(uri.getScheme().equals(ContentResolver.SCHEME_FILE)){
                uri1 = FileProvider.getUriForFile(requireContext(), authorities, new File(uri.toString()));
            }else{
                uri1 = uri;
            }

            Cursor cursor = requireContext().getContentResolver().query(uri1, null, null, null, null, null);
            if(cursor != null){
                cursor.moveToFirst();
                this.cropCallback = callback;

                Intent intent = new Intent("com.android.camera.action.CROP");

                //文件名
                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                String mimeType = requireContext().getContentResolver().getType(uri);
                String imageName = System.currentTimeMillis()+"."+ MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
                if (Build.VERSION.SDK_INT >= 29){
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.MediaColumns.DISPLAY_NAME,imageName);
                    values.put(MediaStore.MediaColumns.MIME_TYPE,mimeType);
                    values.put("relative_path", Environment.DIRECTORY_DCIM);
                    outUri = requireContext().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,values);
                }else{
                    outUri = Uri.fromFile(new File(requireContext().getExternalCacheDir().getAbsolutePath(), imageName));
                }

                requireContext().grantUriPermission(
                        requireContext().getPackageName(),
                        outUri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION
                );
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.putExtra("noFaceDetection", true); //去除默认的人脸识别，否则和剪裁匡重叠
                intent.setDataAndType(uri1, requireContext().getContentResolver().getType(uri));
                intent.putExtra("crop", "true"); // crop=true 有这句才能出来最后的裁剪页面.
                intent.putExtra("output", outUri);
                intent.putExtra("outputFormat", "JPEG"); // 返回格式

                int ax = aspectX;
                int ay = aspectY;
                if (ax != 0 && ay != 0) {
                    if (ax == ay && Build.MANUFACTURER.equals("HUAWEI")) {
                        ax = 9998;
                        ay = 9999;
                    }
                    intent.putExtra("aspectX", ax); // 这两项为裁剪框的比例.
                    intent.putExtra("aspectY", ay); // x:y=1:2
                }
                if (outputX != 0 && outputY != 0) {
                    intent.putExtra("outputX", outputX);
                    intent.putExtra("outputY", outputY);
                }
                intent.putExtra("return-data", false);
                startActivityForResult(
                        intent,REQUEST_CODE_CROP
                );

                cursor.close();
            } else if(uri1 != null && !TextUtils.isEmpty(uri1.getPath())){
                this.cropCallback = callback;

                String imageName = System.currentTimeMillis()+".jpg";
                outUri = Uri.fromFile(new File(requireContext().getExternalCacheDir().getAbsolutePath(), imageName));

                Intent intent = new Intent("com.android.camera.action.CROP");
                requireContext().grantUriPermission(
                        requireContext().getPackageName(),
                        outUri,
                        Intent.FLAG_GRANT_READ_URI_PERMISSION
                );
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.putExtra("noFaceDetection", true); //去除默认的人脸识别，否则和剪裁匡重叠
                intent.setDataAndType(uri1, "image/*");
                intent.putExtra("crop", "true"); // crop=true 有这句才能出来最后的裁剪页面.
                intent.putExtra("output", outUri);
                intent.putExtra("outputFormat", "JPEG"); // 返回格式

                int ax = aspectX;
                int ay = aspectY;
                if (ax != 0 && ay != 0) {
                    if (ax == ay && Build.MANUFACTURER.equals("HUAWEI")) {
                        ax = 9998;
                        ay = 9999;
                    }
                    intent.putExtra("aspectX", ax); // 这两项为裁剪框的比例.
                    intent.putExtra("aspectY", ay); // x:y=1:2
                }
                if (outputX != 0 && outputY != 0) {
                    intent.putExtra("outputX", outputX);
                    intent.putExtra("outputY", outputY);
                }
                intent.putExtra("return-data", false);
                startActivityForResult(
                        intent,REQUEST_CODE_CROP
                );
            }
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            if(resultCode == Activity.RESULT_OK){
                switch (requestCode){
                    case REQUEST_CODE_CROP:
                        //裁剪
                        Uri uri;
                        if(Build.VERSION.SDK_INT >= 29){
                            if(ContentResolver.SCHEME_FILE.equals(outUri.getScheme())){
                                uri = FileProvider.getUriForFile(requireContext(), authorities, uriToFileQ(getContext(),outUri));
                            }else{
                                uri = outUri;
                            }
                        }else{
                            uri = outUri;
                        }
                        if(cropCallback != null){
                            cropCallback.onResult(uri, true, "");
                            cropCallback = null;
                        }
                        break;
                    case REQUEST_CODE_CAMERA:
//                        Tool.showToast("cameraPath: $cameraPath");

                        if(TextUtils.isEmpty(cameraPath)){
                            ToastUtils.show(getContext(),"拍照失败");
                            return;
                        }
                        Uri uriCamera;
                        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                            uriCamera = FileProvider.getUriForFile(requireContext(),
                                    authorities,new File(cameraPath));
                        }else{
                            uriCamera = Uri.fromFile(new File(cameraPath));
                        }

//                        Tool.showToast("cameraPath: ${uri.scheme} ${uri.path}");
                        if(cameraCallback != null){
                            cameraCallback.onResult(uriCamera, true, "");
                            cameraCallback = null;
                        }
                        break;
                    case REQUEST_CODE_SELECT:
                        if(data != null){
                            Uri uriSelect = data.getData();
                            if(selectCallback != null){
                                selectCallback.onResult(uriSelect, true, "");
                                selectCallback = null;
                            }
                        }
                        break;
                }
            }else{
                switch (requestCode){
                    case REQUEST_CODE_CROP:
                        ToastUtils.show(getContext(),"裁剪失败");
                        break;
                    case REQUEST_CODE_CAMERA:
                        ToastUtils.show(getContext(),"拍照失败");
                        break;
                    case REQUEST_CODE_SELECT:
                        ToastUtils.show(getContext(),"选择图片失败");
                        break;
                }
            }
        }
    }

    private static PhotoFragment getPhotoFragment(FragmentManager manager){
        Fragment fragment = manager.findFragmentByTag("photoFragmen");
        if(fragment instanceof PhotoFragment){
            return (PhotoFragment) fragment;
        }

        PhotoFragment photoFragment = new PhotoFragment();
        manager.beginTransaction()
                .add(photoFragment,"photoFragmen")
                .commitAllowingStateLoss();
        manager.executePendingTransactions();
        return photoFragment;
    }

    private static File uriToFileQ(Context context, Uri uri) {
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            if (!TextUtils.isEmpty(uri.getPath())) {
                return new File(uri.getPath());
            }
        } else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            //把文件保存到沙盒
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = null;
            Cursor cursor = contentResolver.query(uri, null, null, null, null);
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                }
                cursor.close();
            }
            if (TextUtils.isEmpty(displayName)) {
                displayName = System.currentTimeMillis() + new Random().nextInt(9999) + "."
                        + MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));
            }

            InputStream ios = null;
            try {
                ios = contentResolver.openInputStream(uri);
                if (ios != null) {
                    File file = new File(context.getExternalCacheDir().getAbsolutePath() + File.separator + displayName);

                    FileOutputStream fos = new FileOutputStream(file);
//                    FileUtils.copy(ios, fos);

                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = ios.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }

                    fos.close();
                    ios.close();
                    return file;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public interface PhotoCallback{
        void onResult(Uri uri, boolean success, String s);
    }


}